package com.qf.strategy.listener;


import com.qf.strategy.feign.CacheService;
import com.qf.strategy.utils.FilterOrdersUtil;
import com.qianfeng.smsplatform.common.constants.CacheConstants;
import com.qianfeng.smsplatform.common.constants.RabbitMqConsants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by jackiechan on 2020-02-28 11:18
 *
 * @Author jackiechan
 */
@Component
public class ReceiveFiterChangeListener {
    @Resource
    private CacheService cacheService;
    private static final Logger LOGGER = LoggerFactory.getLogger(ReceiveFiterChangeListener.class);
    private ApplicationContext context;

    @StreamListener(RabbitMqConsants.TOPIC_FILTER_UPDATE)//监听指定的交换机,实际上是创建了一个随机的队列绑定到这个交换机
    public void onMessage(String message) {
        LOGGER.error("收到了过滤器发生变化的消息");
        //当这个方执行的时候代表有人更新了过滤器的数据然后发送了一个消息给我们
        //我们在这里需要重新加载过滤器数据,清空本地缓存,替换掉
        Map<String, String> filtersOrderMaplocal = new ConcurrentHashMap<>(); //使用本地临时变量先保存数据
        Set<String> keys = cacheService.getKeys(CacheConstants.CACHE_PREFIX_SMS_FILTERS_ORDER + "*");
        for (String key : keys) {
            String filterorder = cacheService.get(key);
            filtersOrderMaplocal.put(key, filterorder);//将从 reids 中获取到的每一条过滤器的数据缓存到本地
        }
        FilterOrdersUtil.filtersOrderMap.clear();//清空原先的缓存
        FilterOrdersUtil.filtersOrderMap.putAll(filtersOrderMaplocal);//添加最新数据,因为我们需要清空原始缓存,为了防止上面的代码出现异常导致我们提前清空了缓存,所以我们使用本地临时变量先保存数据,没有异常的情况下再清空缓存,然后全部加进来
        filtersOrderMaplocal.clear();
        filtersOrderMaplocal = null;//清理本地临时变量
//        context.publishEvent();
    }
}
